#ifndef __M_FMT_H__
#define __M_FMT_H__

#include <ctime>
#include <vector>
#include <cassert>
#include <sstream>
#include "message.hpp"
#include "level.hpp"

namespace bitlog
{
    // 格式化子类基类
    class FormatItem
    {
    public:
        using ptr = std::shared_ptr<FormatItem>;
        virtual ~FormatItem() {}
        virtual void format(std::ostream &out,const LogMsg &msg) = 0;
    };
    // 格式化子项子类：消息，等级，时间，文件名，行号，线程id，日志器名，制表符，换行，其他
    class MsgFormatItem : public FormatItem
    {
    public:
        // MsgFormatItem(const std::string &str=""){}
        /*void*/ void format(std::ostream &out,const LogMsg &msg) override
        {
            out << msg._payload;
        } 
    };
    class LevelFormatItem : public FormatItem
    {
    public:
        // LevelFormatItem(const std::string &str=""){}
        void format(std::ostream &out,const LogMsg &msg) override
        {
            out << LogLevel::toString(msg._level);
        }
    };
    /*class NameFormatItem:public FormatItem{
        public:
        NameFormatItem(const std::string &str=""){}
        virtual void format(std::ostream &os,const LogMsg &msg){
            os<<msg._name;
        } 
    };*/
    /*class ThreadFormatItem:public FormatItem{
        public:
        ThreadFormatItem(const std::string &str=""){}
        virtual void format(std::ostream &os,const LogMsg &msg){
            os<<msg._tid;
        }
    };*/
    class TimeFormatItem : public FormatItem
    {

    public:
        TimeFormatItem(const std::string &fmt = "%H:%M:%S") : _time_fmt(fmt)
        {
            // if(format.empty()) _time_fmt="%H:%M:%S";
        }
        void format(std::ostream &os,const LogMsg &msg) override
        {
            // time_t t=msg._ctime;
            struct tm t;
            localtime_r(&msg._ctime, &t);
            char tmp[32];
            strftime(tmp, 31, _time_fmt.c_str(), &t);
            os << tmp;
        }

    private:
        std::string _time_fmt;
    };
    // 文件名
    class FileFormatItem : public FormatItem
    {
    public:
        // LevelFormatItem(const std::string &str=""){}
        void format(std::ostream &out,const LogMsg &msg) override
        {
            out << msg._file;
        }
    };
    // 行号
    class LineFormatItem : public FormatItem
    {
    public:
        // LevelFormatItem(const std::string &str=""){}
        void format(std::ostream &out,const LogMsg &msg) override
        {
            out << msg._line;
        }
    };
    // 线程id
    class ThreadFormatItem : public FormatItem
    {
    public:
        // LevelFormatItem(const std::string &str=""){}
        void format(std::ostream &out,const LogMsg &msg) override
        {
            out << msg._tid;
        }
    };
    // 日志器名称
    class LoggerFormatItem : public FormatItem
    {
    public:
        // LevelFormatItem(const std::string &str=""){}
        void format(std::ostream &out,const LogMsg &msg) override
        {
            out << msg._logger;
        }
    };
    class TabFormatItem : public FormatItem
    {
    public:
        // LevelFormatItem(const std::string &str=""){}
        void format(std::ostream &out,const LogMsg &msg) override
        {
            out << "\t";
        }
    };
    class NLineFormatItem : public FormatItem
    {
    public:
        // LevelFormatItem(const std::string &str=""){}
        void format(std::ostream &out, const LogMsg &msg) override
        {
            out << "\n";
        }
    };
    class OtherFormatItem : public FormatItem
    {
    public:
        OtherFormatItem(const std::string &str) : _str(str) {}
        void format(std::ostream &out,const LogMsg &msg) override
        {
            out << _str;
        }

    private:
        std::string _str;
    };
    class Formatter
    {
    public:
        using ptr =std::shared_ptr<Formatter>;
        Formatter(const std::string &pattern = "[%d{%H:%M:%S}][%t][%c][%f:%l][%p]%T%m%n") : _pattern(pattern) {
            assert(parsePattern());
        }
        // 对msg进格式化
        void format(std::ostream &out, const LogMsg &msg)
        {
            for (auto &item : _items)
            {
                item->format(out, msg);
            }
        }
        std::string format(const LogMsg &msg)
        {
            std::stringstream ss;
            format(ss, msg);
            return ss.str();
        }
    private:
        //对格式化规则字符串进行解析
        bool parsePattern()
        {
            //1.对格式化规则字符串进行解析
            std::vector<std::pair<std::string,std::string>> fmt_order;
            size_t pos=0;
            std::string key,val;
            while(pos<_pattern.size())
            {
                if(_pattern[pos]!='%')
                {
                    val.push_back(_pattern[pos++]);
                    continue;
                }
                if(pos+1<_pattern.size()&&_pattern[pos+1]=='%')
                {
                    val.push_back('%');
                    pos+=2;
                    continue;
                }
                if(val.empty()==false)
                {
                    fmt_order.push_back(std::make_pair("",val));
                    val.clear();
                }
                pos+=1;
                if(pos==_pattern.size())
                {
                    std::cout<<"%之后，没有对应的格式化字符！\n";
                    return false;
                }
                key=_pattern[pos];
                pos+=1;
                if(pos<_pattern.size()&&_pattern[pos]=='{')
                {
                    pos+=1;
                    while(pos<_pattern.size()&&_pattern[pos]!='}')
                    {
                        val.push_back(_pattern[pos++]);
                    }
                    if(pos==_pattern.size())
                    {
                        std::cout<<"子规则{}匹配出错\n";
                        return false;
                    }
                    pos+=1;
                }
                fmt_order.push_back(std::make_pair(key,val));
                key.clear();
                val.clear();
            }

            //2.根据解析得到的数据初始化子项数组成员
            for(auto& it:fmt_order)
            {
                _items.push_back(createItem(it.first,it.second));
            }
            return true;
        }

        FormatItem::ptr createItem(const std::string &key, const std::string &val)
        {
            if (key == "d")
                return std::make_shared<TimeFormatItem>(val);
            if (key == "t")
                return std::make_shared<ThreadFormatItem>();
            if (key == "c")
                return std::make_shared<LoggerFormatItem>();
            if (key == "f")
                return std::make_shared<FileFormatItem>();
            if (key == "l")
                return std::make_shared<LineFormatItem>();
            if (key == "p")
                return std::make_shared<LevelFormatItem>();
            if (key == "T")
                return std::make_shared<TabFormatItem>();
            if (key == "m")
                return std::make_shared<MsgFormatItem>();
            if (key == "n")
                return std::make_shared<NLineFormatItem>();
            return std::make_shared<OtherFormatItem>(val);
        }

    private:
        std::string _pattern;
        std::vector<FormatItem::ptr> _items;
    };

}

#endif